﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using WebClient.Models;
using WebClient.Models.ViewModels;
using WebClient.Helpers;
using WebClient.CF_DAL_WS;

namespace WebClient.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(FormCollection forms)
        {
            var errText = string.Empty;
            string username = forms.GetValues("LogOn_UserName")[0];
            string password = forms.GetValues("LogOn_Password")[0];
            string url = string.Empty;
            if (forms.GetValues("navbar_url") != null)
            {
                url = forms.GetValues("navbar_url")[0];
            }

            if ((errText = DALService.Instance.Validation_ValidateUser(username, password)) == string.Empty)
            {
                var Users = DALService.Instance.Users_SelectAll().Where(n => n.UserName == username).ToList();
                var role = Users[0].Role.Name.ToUpper();
                SetCookieMember(username, password, role);
                if (!String.IsNullOrEmpty(url))
                {
                    if (url.Contains("Approve"))
                    {
                        string idrestaurant = forms.GetValues("navbar_idrestaurant")[0];
                        return RedirectToAction("Approve", "Home", new { idrestaurant = idrestaurant });
                    }
                    return Redirect(url);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ViewData["LoginStatus"] = errText;
                if (url != "")
                {
                    return RedirectToAction("Index", "Home"); 
                }
                return View();
            }
        }

        private void SetCookieMember(string username, string password, string role, bool rememberme = true)
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            HttpCookie SlmSessionId = new HttpCookie("SLMFSessionId");
            HttpCookie SlmRole = new HttpCookie("SLMFRole");
            DateTime dateSLMF = DateTime.Now;
            // UserName
            SlmMemberCookie.Value = username;
            SlmMemberCookie.Expires = dateSLMF.AddDays(3);
            // Password
            SlmSessionId.Value = password;
            SlmSessionId.Expires = dateSLMF.AddDays(4);
            // Role
            SlmRole.Value = role;
            SlmRole.Expires = dateSLMF.AddDays(4);
            if (rememberme)
            {
                SlmMemberCookie.Expires = dateSLMF.AddDays(7);
                SlmSessionId.Expires = dateSLMF.AddDays(8);
                SlmRole.Expires = dateSLMF.AddDays(8);
            }
            Response.Cookies.Add(SlmMemberCookie);
            Response.Cookies.Add(SlmSessionId);
            Response.Cookies.Add(SlmRole);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            SlmMemberCookie = Request.Cookies["SLMFMembers"];
            if (SlmMemberCookie != null && SlmMemberCookie.Value != "" &&
                     SlmMemberCookie.Value != null)
            {
                SlmMemberCookie.Expires = new System.DateTime(2005, 1, 1);
                SlmMemberCookie.Value = null;
                Response.Cookies.Add(SlmMemberCookie);
            }
            FormsAuthentication.SignOut();
            return View("LogOn");
        }

        public ActionResult LogOffHome()
        {
            HttpCookie SlmMemberCookie = new HttpCookie("SLMFMembers");
            SlmMemberCookie = Request.Cookies["SLMFMembers"];
            if (SlmMemberCookie != null && SlmMemberCookie.Value != "" &&
                     SlmMemberCookie.Value != null)
            {
                SlmMemberCookie.Expires = new System.DateTime(2005, 1, 1);
                SlmMemberCookie.Value = null;
                Response.Cookies.Add(SlmMemberCookie);
            }
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(FormCollection forms)
        {
            var nguoiDungInfo = new AddUsersViewModel
            {
                UserName = forms.GetValues("NguoiDung_UserName")[0],
                Password = forms.GetValues("NguoiDung_Password")[0],
                Email = forms.GetValues("NguoiDung_Email")[0],
                Name = forms.GetValues("NguoiDung_Name")[0],
                Phone = forms.GetValues("NguoiDung_Phone")[0],
                Address = forms.GetValues("NguoiDung_Address")[0],
                Role = new RoleDTO
                {
                    Name = "customer"
                }
            };
            var result = _repUsers.Insert(nguoiDungInfo);
            DataTransferViewModel data;
            // Insert successful
            if (result == string.Empty)
            {
                SetCookieMember(nguoiDungInfo.UserName, nguoiDungInfo.Password, nguoiDungInfo.Role.Name);
                ViewData["RegisterResult"] = "You have registered successfully!";
                data = new DataTransferViewModel
                {
                    EnumViewModelType = EnumViewModel.HOME_DETAILOF_USERS,
                    UserName = nguoiDungInfo.UserName
                };
                return View("UserInfo", CreateViewModel(data));
            }

            // Register fail
            ViewData["RegisterResult"] = result;
            ViewData["RegisterUserName"] = nguoiDungInfo.UserName;
            ViewData["RegisterPassword"] = nguoiDungInfo.Password;
            ViewData["RegisterEmail"] = nguoiDungInfo.Email;
            ViewData["RegisterName"] = nguoiDungInfo.Name;
            ViewData["RegisterPhone"] = nguoiDungInfo.Phone;
            ViewData["RegisterAddress"] = nguoiDungInfo.Address;

            data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View("Register", CreateViewModel(data));
        }

        public ActionResult UserInfo(string username)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_USERS,
                UserName = username
            };
            return View("UserInfo", CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateAccount(FormCollection forms)
        {
            var nguoiDungInfo = new UsersDTO
            {
                ID = Guid.Parse(forms.GetValues("NguoiDung_ID")[0]),
                Email = forms.GetValues("NguoiDung_Email")[0],
                Name = forms.GetValues("NguoiDung_Name")[0],
                Phone = forms.GetValues("NguoiDung_Phone")[0],
                Address = forms.GetValues("NguoiDung_Address")[0]
            };
            var result = _repUsers.Update(nguoiDungInfo);

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DETAILOF_USERS,
                UserName = forms.GetValues("NguoiDung_UserName")[0],
                InfoText = result ? "Information has been updated" : "Cannot update information"
            };
            return View("UserInfo", CreateViewModel(data));
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [UserAuthorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [UserAuthorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(FormCollection forms)
        {
            var user = DALService.Instance.Users_SelectByUserName(forms.GetValues("NguoiDung_UserName")[0]);
            if (DALService.Instance.Validation_ValidateUser(user.UserName, forms.GetValues("NguoiDung_OldPassword")[0]) == string.Empty)
            {
                var result = _repUsers.ChangePassword(user.UserName, forms.GetValues("NguoiDung_OldPassword")[0], forms.GetValues("NguoiDung_NewPassword")[0]);
                if (result)
                {
                    SetCookieMember(user.UserName, forms.GetValues("NguoiDung_NewPassword")[0], user.Role.Name);
                    return RedirectToAction("ChangePasswordSuccess");
                }
            }   

            ViewData["ChangePasswordResult"] = "Cannot change password, the current password is incorrect or the new password is invalid.";
            ViewData["ChangePasswordOldPassword"] = forms.GetValues("NguoiDung_OldPassword")[0];
            ViewData["ChangePasswordNewPassword"] = forms.GetValues("NguoiDung_NewPassword")[0];
            ViewData["ChangePasswordConfirmNewPassword"] = forms.GetValues("NguoiDung_ConfirmPassword")[0];
            return View("ChangePassword");
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult ResetPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ResetPassword(FormCollection forms)
        {
            var username = forms.GetValues("NguoiDung_UserName")[0];
            var email = forms.GetValues("NguoiDung_Email")[0];
            var result = _repUsers.ResetPassword(username, email);

            // Cannot reset password
            if (result == string.Empty)
            {
                return RedirectToAction("PasswordResetSuccess");
            }
            else
            {
                ViewData["ResetPasswordResult"] = result;
            }
            return View();
        }

        public ActionResult PasswordResetSuccess()
        {
            return View();
        }

        public ActionResult PasswordResetFailed()
        {
            return View();
        }

    }
}
